package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.admin.dto.LoginDto;
import com.heima.admin.entity.AdUser;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.IAdUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-06-19
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements IAdUserService {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public ResponseResult login(LoginDto loginDto) {
        //判断用户名和密码是否为空
        if (loginDto==null || StringUtils.isEmpty(loginDto.getName())||StringUtils.isEmpty(loginDto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据用户名查询用户
        LambdaQueryWrapper<AdUser> query = new LambdaQueryWrapper<>();
        query.eq(AdUser::getName,loginDto.getName());
        AdUser one = this.getOne(query);
        //不存在提示用户不存在
        if (one==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //存在的话,取出用户数据库中的salt
        String salt = one.getSalt();
        //使用数据库中的密码+salt
        String password = loginDto.getPassword()+salt;
        String md5 = DigestUtils.md5DigestAsHex(password.getBytes());
        //密码错误
        if (!md5.equals(one.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //密码正确,使用jwt生成token
        HashMap<String, Object> userInfo = new HashMap<>();
        userInfo.put("userId",one.getId());
        String token = AppJwtUtil.getToken(userInfo);

        //把token 保存到redis中
        String key="user"+one.getId();
        redisTemplate.opsForValue().set(key,token);
        redisTemplate.expire(key,24L, TimeUnit.HOURS);

        //给前端返回对应格式的格式
        AdUser adUser=new AdUser();
        adUser.setName(one.getName());
        HashMap<String, Object> map = new HashMap<>();
        map.put("user",adUser);
        map.put("token",token);
        return ResponseResult.okResult(map);

    }
}
